package com.cloudcc.mobile.network;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.ImageInfo;
import com.cloudcc.mobile.entity.CustomerEntity;
import com.cloudcc.mobile.entity.Khbf;
import com.cloudcc.mobile.entity.ManyImage;
import com.cloudcc.mobile.entity.chat.DraftBox;
import com.cloudcc.mobile.entity.chat.DraftKhbf;
import com.cloudcc.mobile.entity.map.MapLocation;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.parser.ImageParser;
import com.cloudcc.mobile.parser.KhbfParser;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.NotificationUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UploadClient;
import com.cloudcc.mobile.util.UrlTools;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/** 
 * 签到的工具集合类
* @author wangzhiqiang
* @date 2015-6-4 上午9:57:39 
*  @deprecated 使用
*/
public class QianDaoUtils {
	private Context context;
	private List<String> pzlist;
	private List<AddImageInfo> list;
	private CustomerEntity kehu;
	private MapLocation location;
	private int num;
	private String text;
	public QianDaoUtils(Context context,int num){
		this.context=context;
		this.num=num;
		pzlist=new ArrayList<String>();
	}

	/**
	 * 后台发送签到
	 */
	public void sendQianDao(List<AddImageInfo> list,MapLocation location,CustomerEntity kehu,String text){
		NotificationUtils.showNotification(context, "发送中...", "签到", "签到发送中...", num);
		this.list=list;
		this.location=location;
		this.kehu=kehu;
		this.text=text;
		send();
	}

	private void send() {
		if(Tools.isNull(text)){
			text="我拜访了这个客户！";
		}
		for (int i = 0; i < list.size(); i++) {
			File file=new File(list.get(i).getImagePath());
			if(!file.exists()){
				list.remove(i);
			}
		}
		final String[] imagepaths=new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			imagepaths[i]=list.get(i).getImagePath();
		}
		if(list.size()>0){//有图
			ManyImage images=new ManyImage();
			images.setImgName(Tools.getTimeName(System.currentTimeMillis()));
			images.setAddress(location.getAddress());
			images.setImgHeight("");
			images.setImgWidth("");
			images.setImgId("");
			images.setImgType("png");
			images.setLatitude(location.getLatitude());
			images.setLongitude(location.getLongitude());
			final String data=Json.toJson(images);
			new Thread(){public void run() {
				try {
					String result=null;
					String Data = URLDecoder.decode(data, "UTF-8");
					final String url=UrlTools.url+UrlTools.imgupload_path+Data+"&binding="+AppContext.binding;
					result=UploadClient.sendMany(imagepaths, url);
					if(result!=null){
						Message msg=handler.obtainMessage(1);
						msg.obj=result;
						msg.sendToTarget();
					}else{
						handler.obtainMessage(-3);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} 
			}}.start();
		}else{
			handler.sendEmptyMessage(2);
		}

	}
	Handler handler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				String result=(String) msg.obj;
				if(Tools.isNull(result)){
					ErrorLoading();
					return;
				}
				ImageInfo info=ImageParser.getImageInfo(result);
				boolean isresult=info.isResult();
				if(isresult){
					String images=info.getImgId();
					String[] img=images.split(",");
					for (int i = 0; i < img.length; i++) {
						pzlist.add(img[i]);
					}
					addkhbf();
				}else{
					ErrorLoading();
				}
				break;
			case 2:
				addkhbf();
				break;
			case -3:
				ErrorLoading();
				break;
			}
			super.handleMessage(msg);
		}

	};
	/**
	 * 错误处理
	 */
	private void ErrorLoading() {
		try {
			saveDraftBox();
			Tools.showInfo(context, "签到失败！已保存草稿箱");
			NotificationUtils.clearNotification(context, num);
			//Intent finish=new Intent(AppContext.MAP_ACTIVITY_FINISH);
			//context.sendBroadcast(finish);
			Intent caogao=new Intent(AppContext.CAOGAO_NUM);
			context.sendBroadcast(caogao);
		} catch (DbException e) {
			Tools.handle(e);
		}
	}
	/**
	 * 添加客户拜访
	 */
	protected void addkhbf() {
		Khbf  khbf=new Khbf();
		khbf.setBfkhccname(kehu.getName());
		khbf.setBfkh(kehu.getId());
		khbf.setBfzj(text);
		khbf.setBfsj(Tools.getTime(System.currentTimeMillis()));
		khbf.setBflx("临时拜访");
		if(list.size()>0){
			for (int i = 0; i < 9; i++) {
				if(pzlist.size()<i+1){
					pzlist.add("");
				}
			}
			khbf.setPz(pzlist.get(0));
			khbf.setPz1(pzlist.get(1));
			khbf.setPz2(pzlist.get(2));
			khbf.setPz3(pzlist.get(3));
			khbf.setPz4(pzlist.get(4));
			khbf.setPz5(pzlist.get(5));
			khbf.setPz6(pzlist.get(6));
			khbf.setPz7(pzlist.get(7));
			khbf.setPz8(pzlist.get(8));
		}
		khbf.setBfwz(location.getAddress());
		String jsonString=Json.toJson(khbf);
		String Data = null;
		try {
			Data = URLEncoder.encode(jsonString, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}//这个是对json数据转编码，必须的
		String url=UrlTools.url+UrlTools.url_path+"serviceName=insertWithRoleRight&objectApiName=khbf&data=["+Data+"]&binding="+AppContext.binding;
		HttpUtils http = new HttpUtils();
		http.configTimeout(15000);
		http.configSoTimeout(15000);
		http.send(HttpRequest.HttpMethod.GET,
				url,
				new RequestCallBack<String>(){
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				boolean  msg=KhbfParser.getUpResult(responseInfo.result);
				if(msg){
						NotificationUtils.clearNotification(context, num);
						//Intent finish=new Intent(AppContext.MAP_ACTIVITY_FINISH);
						//context.sendBroadcast(finish);
						Tools.showInfo(context, "签到成功！");
				}else{
					ErrorLoading();
				}
			}
			@Override
			public void onStart() {
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				ErrorLoading();
			}
		});

	}

	private void saveDraftBox() throws DbException{
		DbUtils db=DbUtils.create(context,UserManager.getManager().getUser().userId+"box.db");
		DraftBox box=new DraftBox();
		box.setType("1");
		box.setTime(Tools.getTime(System.currentTimeMillis()));
		box.setIsNew("1");
		DraftKhbf khbf=new DraftKhbf();
		khbf.setPznum(list.size());
		khbf.setBfText(text);
		khbf.setBfTime(Tools.getTime(System.currentTimeMillis()));
		khbf.setBfwz(location.getAddress());
		khbf.setKehuName(kehu.getName());
		khbf.setKehuId(kehu.getId());
		khbf.setParent(box);
		String pz="";
		if(list.size()>0){
			pz=list.get(0).getImagePath();
			for (int i = 1; i < list.size(); i++) {
				pz=pz+","+list.get(i).getImagePath();
			}
		}
		khbf.setPz(pz);
		box.setKhbf(khbf);
		db.saveBindingId(khbf);
	}
}
